from django.db import models
import uuid
from control.models.User import User
from .basicDimensionModel import BasicDimension


class Dimension(models.Model):
    uuid = models.UUIDField(primary_key=True, auto_created=True,
                            default=uuid.uuid4, editable=False, verbose_name="uuid")
    dimension_name = models.CharField(
        max_length=200, verbose_name="量纲名称", null=False, blank=True, default="")
    dimension_name_en = models.CharField(
        max_length=200, verbose_name="量纲英文名称", null=False, blank=True, default="")
    sei_id = models.CharField(
        max_length=200, verbose_name="量纲编码", null=False, blank=True, default="")
    dimension_description = models.TextField(
        verbose_name='量纲描述', null=False, blank=True, default="")
    dimension_description_en = models.TextField(
        verbose_name='量纲英文描述', null=False, blank=True, default="")
    dimension_comment = models.TextField(
        verbose_name='量纲备注', null=False, blank=True, default="")
    create_person = models.ForeignKey(
        User, verbose_name="创建人", related_name="create_dimension", on_delete=models.DO_NOTHING, null=False)
    create_date = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    modify_person = models.ForeignKey(
        User, verbose_name="修改人", related_name="modify_dimension", on_delete=models.DO_NOTHING, null=False)
    modify_date = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    valid_flag = models.BooleanField(default=True, verbose_name="是否有效")

    class Meta:
        ordering = ['create_date']
        verbose_name = "Dimension"
        verbose_name_plural = "Dimensions"

        constraints = [
            models.UniqueConstraint(fields=['dimension_name'], condition=models.Q(
                valid_flag=True) & ~models.Q(dimension_name=''), name='unique_dimension_name'),
            models.UniqueConstraint(fields=['dimension_name_en'], condition=models.Q(
                valid_flag=True) & ~models.Q(dimension_name_en=''), name='unique_dimension_name_en'),
            models.UniqueConstraint(fields=['sei_id'], condition=models.Q(
                valid_flag=True) & ~models.Q(sei_id=''), name='unique_valid_dimension_sei_id'),
        ]

    def __str__(self):
        return "量纲->" + self.dimension_name
    
    def show_full_name(self):
        if self.dimension_name != "" and self.dimension_name_en != "":
            return "{}({})".format(self.dimension_name, self.dimension_name_en)
        if self.dimension_name != "":
            return self.dimension_name
        if self.dimension_name_en != "":
            return self.dimension_name_en
        return "未命名量纲"
    
    def show_short_name(self):
        if self.dimension_name != "":
            return self.dimension_name
        if self.dimension_name_en != "":
            return self.dimension_name_en
        return "未命名量纲"
    
    def show_short_name_with_dimension_consistency(self):
        # 获取量纲名称
        ans_name = self.dimension_name or self.dimension_name_en or "未命名量纲"

        # 获取有效的 dimension_map
        dimension_maps = DimensionMap.objects.filter(
            dimension=self, basic_dimension__valid_flag=True
        )

        if not dimension_maps.exists():
            return f"{ans_name}[1]"

        # 构建符号-指数映射并排序
        symbol_power_list = sorted(
            {
                dm.basic_dimension.basic_dimension_symbol: dm.power
                for dm in dimension_maps
            }.items(),
            key=lambda x: x[1], reverse=True
        )

        # 拼接维度表达式
        for symbol, power in symbol_power_list:
            ans_name += f"[{symbol}^{power}]" if power != 1 else f"[{symbol}]"

        return ans_name



class DimensionMap(models.Model):
    uuid = models.UUIDField(primary_key=True, auto_created=True,
                            default=uuid.uuid4, editable=False, verbose_name="uuid")
    basic_dimension = models.ForeignKey(
        to=BasicDimension, on_delete=models.DO_NOTHING, verbose_name="基本量纲")
    dimension = models.ForeignKey(
        to=Dimension, on_delete=models.CASCADE, verbose_name="量纲")
    power = models.FloatField(null=False, blank=False,
                              default=1.0, verbose_name="量纲指数")

    class Meta:
        verbose_name = "DimensionMap"
        verbose_name_plural = "DimensionMaps"
        constraints = [
            models.UniqueConstraint(
                fields=['basic_dimension', 'dimension'], name='unique_basic_dimension_dimension'),
        ]

    def __str__(self):
        return self.basic_dimension.basic_dimension_name + " -> " + self.dimension.dimension_name + " : " + str(self.power)
